<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中...">
    <div class="back_bg">
      <h4 class="header_top">商品详情</h4>
      <div style="display: flex; gap: 5px; margin: 10px 0 10px 10px">
        <HButton @click="goback"> 返回 </HButton>
        <HPlainButton @click="editProduct"> 修改商品 </HPlainButton>
        <HPlainButton type="error" @click="changeAll(1)"> 禁用 </HPlainButton>
        <HPlainButton type="error" @click="changeAll(2)"> 删除 </HPlainButton>
        <HPlainButton v-if="activeName == 'second'" @click="addBOM"> 新增BOM关联 </HPlainButton>
      </div>
    </div>
    <el-container class="main">
      <el-aside width="270px">
        <el-card class="box-card">
          <div class="header">
            <h4>{{ proInfo?.model }}</h4>
          </div>
          <el-form label-width="80px" class="form_list">
            <el-form-item label="商品名称">
              <span>{{ proInfo?.name }}</span>
            </el-form-item>
            <el-form-item label="商品品牌">
              <span>{{ proInfo?.brand }}</span>
            </el-form-item>
            <el-form-item label="商品分类">
              <span>{{ proInfo?.type }}</span>
            </el-form-item>
            <el-form-item label="商品货号">
              <span>{{ proInfo?.itemNumber }}</span>
            </el-form-item>
            <el-form-item label="商品编号">
              <span>{{ proInfo?.code }}</span>
            </el-form-item>
            <el-form-item label="商品单位">
              <span>{{ proInfo?.unit }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ proInfo?.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间">
              <span>{{ proInfo?.updateTime }}</span>
            </el-form-item>
            <el-form-item label="商品图片">
              <div class="img_list">
                <el-image
                  v-for="(img, index) in proInfo?.images"
                  :key="img"
                  class="img"
                  :src="img"
                  :zoom-rate="1.2"
                  :preview-src-list="srcList"
                  :initial-index="index"
                  fit="contain"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-aside>
      <el-main class="list">
        <!--商品规格-->
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="商品规格" name="first">
            <div class="tab-header">
              <div class="search flex-align-center">
                <el-input
                  clearable
                  v-model="specName"
                  placeholder="搜索名称"
                  class="input-with"
                  @keyup.enter="getSpecData"
                />
                <el-input
                  clearable
                  v-model="specSKU"
                  placeholder="搜索SKU码"
                  class="input-with"
                  @keyup.enter="getSpecData"
                />
                <HButton type="primary" @click="getSpecData">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索
                </HButton>
              </div>
            </div>
            <div class="spec-table">
              <el-table :data="specList" :border="true" style="width: 100%; margin-top: 15px">
                <el-table-column
                  show-overflow-tooltip
                  type="index"
                  :index="indexMethod"
                  label="序号"
                  width="50"
                />
                <el-table-column
                  show-overflow-tooltip
                  prop="name"
                  label="规格名称"
                  min-width="120"
                />
                <el-table-column show-overflow-tooltip prop="enabled" label="规格状态" width="120">
                  <template #default="scope">
                    <div style="display: flex; justify-content: center">
                      <HStatus :type="scope.row.enabled == true ? 'primary' : 'info'">
                        {{ scope.row.enabled == true ? '启用' : '禁用' }}
                      </HStatus>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="code" label="SKU码" width="120" />
                <el-table-column show-overflow-tooltip prop="price" label="价格" width="120">
                  <template #default="scope">
                    <span>￥{{ scope.row.price }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  show-overflow-tooltip
                  prop="overPrice"
                  label="过保价格"
                  width="120"
                  v-if="nodekey == '2'"
                >
                  <template #default="scope">
                    <span>￥{{ scope.row.overPrice }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  show-overflow-tooltip
                  prop="warrantyDay"
                  label="质保周期"
                  width="120"
                />
                <el-table-column show-overflow-tooltip prop="image" label="规格图片" width="100">
                  <template #default="scope">
                    <el-popover placement="left" :width="200" trigger="hover">
                      <el-image
                        style="width: 100%; height: 120px"
                        :src="scope.row.image"
                        fit="contain"
                      >
                        <template #error>
                          <div class="image-slot">
                            <el-icon><icon-picture /></el-icon>
                          </div>
                        </template>
                      </el-image>
                      <template #reference>
                        <el-icon size="20">
                          <Picture />
                        </el-icon>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="footer-pages">
              <Pagination
                ref="specPage"
                :list_total="specTotal"
                @size-change="getSpecData"
                @current-change="getSpecData"
              />
            </div>
          </el-tab-pane>

          <!--BOM清单-->
          <el-tab-pane label="BOM清单" name="second" v-if="nodekey == '1'">
            <el-table :data="tableData" :border="true" style="width: 100%; margin-top: 15px">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod1"
                label="序号"
                width="50"
              />
              <el-table-column prop="id" label="操作" width="100">
                <template #default="scope">
                  <el-button link type="primary" @click="viewBomDetal(scope.row.id)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip prop="name" label="商品名称" />
              <el-table-column show-overflow-tooltip prop="model" label="商品型号" />
              <el-table-column show-overflow-tooltip prop="type" label="商品分类" />
              <el-table-column show-overflow-tooltip prop="specName" label="商品规格" />
              <el-table-column show-overflow-tooltip prop="specCode" label="SKU编码" />
              <el-table-column show-overflow-tooltip prop="qty" label="子件数量" />
              <el-table-column show-overflow-tooltip prop="remark" label="备注" />
            </el-table>
          </el-tab-pane>

          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="third">
            <span class="text">系统参数</span>
            <el-table :data="paramFields" :border="true" style="width: 100%; margin-bottom: 15px">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod2"
                label="序号"
                width="50"
              />
              <el-table-column show-overflow-tooltip prop="name" label="参数名称" />
              <el-table-column show-overflow-tooltip prop="val" label="参数值">
                <template #default="scope">
                  <span v-if="scope.row.type === 5 || scope.row.type === 6">
                    <img v-for="item in scope.row.optVos" :key="item.id" :src="item.optValue" />
                  </span>
                  <video
                    v-else-if="scope.type === 7"
                    v-for="item in scope.row.optVos"
                    :key="item.id"
                    :src="item.optValue"
                    controls
                    loop
                  ></video>
                  <span v-else>{{ scope.row.optVos.map((o) => o.optValue).join('、') }}</span>
                </template>
              </el-table-column>
            </el-table>
            <span class="text">自定义参数</span>
            <el-table :data="customParams" :border="true" style="width: 100%; margin-bottom: 15px">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod3"
                label="序号"
                width="50"
              />
              <el-table-column show-overflow-tooltip prop="name" label="参数名称" />
              <el-table-column show-overflow-tooltip prop="val" label="参数值" />
            </el-table>
          </el-tab-pane>

          <!--电子说明书-->
          <!-- <el-tab-pane name="fourth" v-if="nodekey == '1'">
            <template #label>
              <span class="custom-tabs-label">
                <span>电子说明书({{ insList.length }})</span>
              </span>
            </template>
            <div class="tab-header">
              <div class="search flex-align-center">
                <el-input
                  clearable
                  v-model="insName"
                  placeholder="搜索名称"
                  class="input-with"
                  @keyup.enter="getInsData"
                />
                <HButton type="primary" @click="getInsData">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索
                </HButton>
              </div>
            </div>
            <el-table :data="insList" :border="true" style="width: 100%; margin-top: 15px">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod4"
                label="序号"
                width="50"
              />
              <el-table-column show-overflow-tooltip prop="name" label="说明书名称" />
              <el-table-column show-overflow-tooltip prop="image" label="说明书图片">
                <template #default="scope">
                  <el-popover placement="left" :width="200" trigger="hover">
                    <el-image
                      style="width: 100%; height: 120px"
                      :src="scope.row.image"
                      fit="contain"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <template #reference>
                      <el-icon size="20">
                        <Picture />
                      </el-icon>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
            <div class="footer-pages">
              <Pagination
                ref="insPage"
                :list_total="insTotal"
                @size-change="getInsData"
                @current-change="getInsData"
              />
            </div>
          </el-tab-pane> -->

          <!--在线视频-->
          <!-- <el-tab-pane name="fifth" v-if="nodekey == '1'">
            <template #label>
              <span class="custom-tabs-label">
                <span>在线视频({{ videoList.length }})</span>
              </span>
            </template>
            <div class="tab-header">
              <div class="search flex-align-center">
                <el-input
                  clearable
                  v-model="videoName"
                  placeholder="搜索名称"
                  class="input-with"
                  @keyup.enter="geVideoData"
                />
                <HButton type="primary" @click="geVideoData">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索
                </HButton>
              </div>
            </div>
            <el-table :data="videoList" :border="true" style="width: 100%; margin-top: 15px">
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod5"
                label="序号"
                width="50"
              />
              <el-table-column show-overflow-tooltip prop="name" label="视频名称" />
              <el-table-column show-overflow-tooltip prop="image" label="视频图片">
                <template #default="scope">
                  <el-popover placement="left" :width="200" trigger="hover">
                    <el-image
                      style="width: 100%; height: 120px"
                      :src="scope.row.image"
                      fit="contain"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <template #reference>
                      <el-icon size="20">
                        <Picture />
                      </el-icon>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
            <div class="footer-pages">
              <Pagination
                ref="videoPage"
                :list_total="videoTotal"
                @size-change="geVideoData"
                @current-change="geVideoData"
              />
            </div>
          </el-tab-pane> -->
          <el-tab-pane label="商品介绍" name="sixth">
            <div v-html="proContent" v-if="proContent != ''"></div>
            <el-empty description="暂无介绍..." v-else />
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <!-- 关联BOM弹窗 -->
    <el-drawer
      v-model="bomDialog"
      title="关联BOM"
      size="80%"
      append-to-body
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div v-loading="bomLoading" element-loading-text="加载中...">
        <h5>组合件：</h5>
        <el-table :data="tableData2" :border="true" style="width: 100%; margin: 10px 0">
          <!--商品型号-->
          <el-table-column show-overflow-tooltip prop="model" label="商品型号" width="180" />

          <!--商品名称-->
          <el-table-column show-overflow-tooltip prop="name" label="商品名称" />

          <!--商品规格-->
          <el-table-column show-overflow-tooltip label="商品规格">
            <template v-slot="scope">
              <el-select v-model="scope.row.spec" placeholder="请选择" clearable>
                <el-option
                  v-for="item in specList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <!--商品分类-->
          <el-table-column show-overflow-tooltip prop="type" label="商品分类" />

          <!--商品品牌-->
          <el-table-column show-overflow-tooltip prop="brand" label="商品品牌" />

          <!--单位-->
          <el-table-column show-overflow-tooltip prop="unit" label="单位" />

          <!--备注-->
          <el-table-column show-overflow-tooltip prop="notes" label="备注">
            <template v-slot="item">
              <el-input v-model="item.row.notes" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
        </el-table>

        <h5>子件：</h5>
        <el-table :data="selfData" :border="true" class="bom_list_tabs" max-height="650">
          <!--序号-->
          <el-table-column show-overflow-tooltip label="序号" width="70" fixed>
            <template v-slot="item">
              <span class="order"> {{ item.$index + 1 }} </span>
              <div class="add_delete">
                <el-icon size="16" color="#007cff" class="add" @click.stop="addLineData">
                  <CirclePlus />
                </el-icon>
                <el-icon
                  color="rgba(245, 108, 108, 1)"
                  size="16"
                  @click.stop="deleteLineData(item.$index, item.row.id)"
                >
                  <CircleClose />
                </el-icon>
              </div>
            </template>
          </el-table-column>

          <!--商品类型-->
          <el-table-column prop="class" label="商品类型" width="100" show-overflow-tooltip>
            <template v-slot="item">
              <el-select v-model="item.row.class" placeholder="请选择成品/配件" clearable>
                <el-option label="成品" value="1" />
                <el-option label="配件" value="2" />
              </el-select>
            </template>
          </el-table-column>

          <!--商品型号-->
          <el-table-column prop="model" label="商品型号" show-overflow-tooltip width="150">
            <template v-slot="item">
              <el-input
                v-model="item.row.model"
                clearable
                placeholder="商品型号"
                :disabled="item.row.class == ''"
              >
                <template #suffix>
                  <el-icon
                    class="el-input__icon"
                    @click="getContPro(item.row.class, item.$index)"
                    v-if="item.row.class != ''"
                  >
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <!--商品名称-->
          <el-table-column prop="name" label="商品名称" show-overflow-tooltip width="150" />

          <!--商品品牌-->
          <el-table-column prop="brand" label="商品品牌" show-overflow-tooltip width="150" />

          <!--商品编号-->
          <el-table-column prop="code" label="商品编号" show-overflow-tooltip width="150" />

          <!--商品分类-->
          <el-table-column prop="type" label="商品分类" show-overflow-tooltip width="150" />

          <!--商品规格-->
          <el-table-column prop="specName" label="商品规格" show-overflow-tooltip width="150" />

          <!--SKU编码-->
          <el-table-column prop="specCode" label="SKU编码" show-overflow-tooltip width="150" />
          <el-table-column prop="num" show-overflow-tooltip width="100">
            <template #header>
              数量
              <el-popover placement="top-start" :width="160" trigger="hover">
                <h5 style="margin-bottom: 10px">批量填充数量</h5>
                <el-input
                  placeholder="请输入"
                  v-model="num"
                  clearable
                  @keyup.enter="changeNumber"
                />
                <div style="display: flex; justify-content: end; margin-top: 10px">
                  <HButton type="primary" :height="20" :padding-lr="6" @click="changeNumber"
                    >确定</HButton
                  >
                </div>
                <template #reference>
                  <span class="multiple_btn">批量</span>
                </template>
              </el-popover>
            </template>
            <template v-slot="item">
              <el-input v-model="item.row.num" placeholder="请输入" clearable></el-input>
            </template>
          </el-table-column>

          <!--单位-->
          <el-table-column prop="unit" label="单位" show-overflow-tooltip width="100" />

          <!--图片-->
          <el-table-column show-overflow-tooltip prop="image" label="图片" width="50">
            <template #default="scope">
              <el-popover placement="left" :width="200" trigger="hover">
                <el-image style="width: 100%; height: 120px" :src="scope.row.image" fit="contain">
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <template #reference>
                  <el-icon size="20">
                    <Picture />
                  </el-icon>
                </template>
              </el-popover>
            </template>
          </el-table-column>

          <!--备注-->
          <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip>
            <template v-slot="item">
              <el-input v-model="item.row.remark" placeholder="请输入" clearable></el-input>
            </template>
          </el-table-column>
        </el-table>

        <!--分页-->
        <div class="footer_pages" v-if="boomId">
          <Pagination
            ref="pagination"
            :list_total="Number(selfData.length)"
            @size-change="getChildList"
            @current-change="getChildList"
          />
        </div>
      </div>

      <template #footer>
        <div style="display: flex; justify-content: flex-end; gap: 10px">
          <HButton is-modal type="primary" @click="saveBOM" @focus="btnCancelFocus">保存</HButton>
          <HButton is-modal @click="bomDialog = false" @focus="btnCancelFocus">取消</HButton>
        </div>
      </template>
    </el-drawer>

    <!-- 关联商品弹窗 -->
    <el-drawer
      v-model="relevanceDialog"
      title="关联商品"
      size="80%"
      append-to-body
      destroy-on-close
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div v-loading="dataLoading" element-loading-text="加载中...">
        <div class="top_search">
          <el-input
            clearable
            v-model="input5"
            placeholder="关键字"
            class="input-with-select mr5"
            :title="input5"
            @keyup.enter="getContData"
          >
          </el-input>
          <div class="search_btn_group">
            <HButton type="primary" @click="getContData">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="input5 = ''">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
        <el-table
          :data="contData"
          :border="true"
          class="bom_list_tabs"
          max-height="740"
          @selection-change="handleChange"
        >
          <el-table-column type="selection" fixed width="40" />
          <el-table-column show-overflow-tooltip label="序号" width="50" fixed>
            <template v-slot="item">
              <span> {{ item.$index + 1 }} </span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="class" label="商品类型" width="100">
            <template #default="scope">
              <span>{{ scope.row.class == 1 ? '成品' : '配件' }} </span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="brand" width="150">
            <template #header>
              品牌
              <el-popover placement="bottom" :width="250" trigger="click">
                <template #reference>
                  <span class="iconfont icon-shaixuan"></span>
                </template>
                <div class="pro-selete">
                  <el-select
                    v-model="brand"
                    placeholder="请选择"
                    clearable
                    class="pro-selete"
                    @change="getContData"
                  >
                    <el-option
                      v-for="item in brandOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="type" width="150">
            <template #header>
              商品分类
              <el-popover placement="bottom" :width="250" trigger="click">
                <template #reference>
                  <span class="iconfont icon-shaixuan"></span>
                </template>
                <div class="pro-selete">
                  <el-select
                    v-model="type"
                    placeholder="请选择"
                    clearable
                    class="pro-selete"
                    @change="getContData"
                  >
                    <el-option
                      v-for="item in typeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="model" label="商品型号" width="150" />
          <el-table-column show-overflow-tooltip prop="name" label="商品名称" width="150" />
          <el-table-column show-overflow-tooltip prop="code" label="商品编号" width="150" />
          <el-table-column show-overflow-tooltip prop="specName" label="商品规格" width="150" />
          <el-table-column show-overflow-tooltip prop="specCode" label="SKU编码" width="150" />
          <el-table-column show-overflow-tooltip prop="unit" label="单位" width="150" />
          <el-table-column show-overflow-tooltip prop="image" label="图片" width="50">
            <template #default="scope">
              <el-popover placement="left" :width="200" trigger="hover">
                <el-image style="width: 100%; height: 120px" :src="scope.row.image" fit="contain">
                  <template #error>
                    <div class="image-slot">
                      <el-icon>
                        <icon-picture />
                      </el-icon>
                    </div>
                  </template>
                </el-image>
                <template #reference>
                  <el-icon size="20">
                    <Picture />
                  </el-icon>
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <div class="footer_pages">
          <Pagination
            ref="pagination2"
            :list_total="typeTotal2"
            @size-change="getContData"
            @current-change="getContData"
          />
        </div>
      </div>

      <template #footer>
        <div style="display: flex; gap: 10px; justify-content: flex-end">
          <HButton type="primary" is-modal @click="saveBtn"> 选中 </HButton>
          <HButton is-modal @click="closeSelect"> 选中并关闭 </HButton>
          <HButton is-modal @click="relevanceDialog = false"> 关闭 </HButton>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, markRaw } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { TabsPaneContext } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import Pagination from '@/components/Pagination/index.vue'
  import {
    MoreFilled,
    Search,
    Picture as IconPicture,
    Warning,
    Delete,
    CircleClose,
    CirclePlus,
    RefreshRight,
  } from '@element-plus/icons-vue'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { useSettingStore } from '@/store/modules/setting'
  import {
    productDisable,
    productDelete,
    getProductDetail,
    getProductSpec,
    getInsList,
    getVideoList,
    getIntroduce,
    getProductParam,
    getSpareDetail,
    getSpareSpec,
    getSparePara,
    getSpareIntroduce,
    getGoodsBoomList,
    brandPageSelect,
    typePageSelect,
    getSpareBoomList,
    saveGoodsBoom,
    getProductBoom,
    getProductBoomDetail,
    getProductBoomChildList,
  } from '@/api/goodsInfo'
  import HButton from '@/components/common/button/HButton.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.good.goodDetail,
  })

  //列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }
  const indexMethod1 = (index: number) => {
    return (index + 1) * 1
  }
  const indexMethod2 = (index: number) => {
    return (index + 1) * 1
  }
  const indexMethod3 = (index: number) => {
    return (index + 1) * 1
  }
  const indexMethod4 = (index: number) => {
    return (index + 1) * 1
  }
  const indexMethod5 = (index: number) => {
    return (index + 1) * 1
  }

  const TagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const nodekey = localStorage.getItem('nodeKey')
  const srcList = ref([])
  const activeName = ref('first')
  const input5 = ref('') // 关键字
  const field = ref('') // 自定义字段
  const bomDialog = ref(false)
  const relevanceDialog = ref(false)
  const tableData = ref([])
  const tableData2 = []
  const selfData = ref([
    {
      class: '1',
      id: null,
      brand: '',
      code: '',
      goodsId: '',
      goodsSpecId: '',
      model: '',
      name: '',
      num: '1',
      unit: '',
      type: '',
      specId: '',
      specName: '',
      specCode: '',
      image: '',
      remark: '',
    },
  ])
  const num = ref('')

  const pagination = ref() // 商品分页Dom

  const pagination2 = ref() // 商品分页Dom
  const typeTotal2 = ref() // 商品总数量

  // 刷新页面
  const refresh = () => {
    useSettingStore().setReload()
  }

  // 选项切换
  const handleClick = async (tab: TabsPaneContext) => {
    loading.value = true
    if (tab.props.name == 'first') {
      await getSpecData()
      loading.value = false
    }
    if (tab.props.name == 'second') {
      await getBomData()
      loading.value = false
    }
    if (tab.props.name == 'third') {
      await getParaData()
      loading.value = false
    }
    if (tab.props.name == 'fourth') {
      // await getInsData()
      loading.value = false
    }
    if (tab.props.name == 'fifth') {
      // await geVideoData()
      loading.value = false
    }
    if (tab.props.name == 'sixth') {
      await getProContent()
      loading.value = false
    }
  }

  // 修改商品
  const editProduct = () => {
    if (nodekey == '1') {
      router.push({
        path: '/commodity/commodi/edit/' + route.params.id,
      })
    } else {
      router.push({
        path: '/commodity/commodi/editSpare/' + route.params.id,
      })
    }
  }

  const goback = () => {
    refresh()
    TagsViewStore.delView(router.currentRoute.value.path)
    router.push({ path: '/commodity/commodi' })
  }

  // 封装修改状态的方法
  const changeDisable = (type, name, method, arr, status) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的${name}`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的${name}?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != '3') {
        // 批量启用/禁用
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 2000,
          })
          if (res.data.code == 20000) {
            getProDetail()
          }
        })
      } else {
        // 批量删除
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: res.data.success ? 'success' : 'error',
            duration: 2000,
          })
          if (res.data.code == 20000) {
            goback()
          }
        })
      }
    })
  }

  // 禁用/删除商品
  const changeAll = (n: number) => {
    if (n == 1) {
      changeDisable('禁用', '商品', productDisable, [route.params.id], true)
    } else {
      changeDisable('删除', '商品', productDelete, [route.params.id], '3')
    }
  }

  const loading = ref(true)
  const proInfo = ref() // 商品信息

  const specList = ref([]) // 规格列表
  const specName = ref('') // 规格名称
  const specSKU = ref('') // 规格SKU码
  const specPage = ref() // 商品规格分页Dom
  const specTotal = ref() // 总数目

  const paramsName = ref('') // 参数名称
  const paramFields = ref([]) // 系统参数列表
  const customParams = ref([]) // 自定义参数列表

  const insName = ref('') // 说明书名称
  const insList = ref([]) // 说明书列表
  const insPage = ref() // 商品规格分页Dom
  const insTotal = ref() // 总数目

  const videoName = ref('') // 视频名称
  const videoList = ref([]) // 视频列表
  const videoPage = ref() // 视频分页Dom
  const videoTotal = ref() // 总数目

  const proContent = ref() // 商品内容简介

  const brand = ref() // 品牌ID
  const brandOptions = ref([]) // 品牌下拉数据

  const type = ref() // 分类ID
  const typeOptions = ref([]) // 分类下拉数据

  const typeName = ref('') // 商品类型
  const bomIndex = ref() // 当前点击

  const contData = ref([]) // 关联的商品数据
  const boomChildVos = ref([]) // 子件列表
  const boomId = ref() // 子件ID
  const delBoomChildIds = ref([]) // 删除Boom子件ID集合

  const bomLoading = ref(false)
  const dataLoading = ref(false)

  // 获取分页数据
  const getPagingData = (obj, name) => {
    return {
      name: name,
      limit: obj.size,
      page: obj.current,
    }
  }

  // 获取商品详情
  const getProDetail = () => {
    if (nodekey == '1') {
      getProductDetail(route.params.id).then((res) => {
        proInfo.value = res.data.data.row
        if (res.data.data.row.images.length != 0) {
          res.data.data.row.images.forEach((item) => {
            srcList.value.push(item)
          })
        }
        tableData2.push({
          model: res.data.data.row.model,
          name: res.data.data.row.name,
          type: res.data.data.row.type,
          brand: res.data.data.row.brand,
          unit: res.data.data.row.unit,
          spec: '',
          notes: '',
        })
        loading.value = false
      })
    } else {
      getSpareDetail(route.params.id).then((res) => {
        proInfo.value = res.data.data.row
        if (res.data.data.row.images.length != 0) {
          res.data.data.row.images.forEach((item) => {
            srcList.value.push(item)
          })
        }
        loading.value = false
      })
    }
  }

  // 获取规格列表
  const getSpecData = async () => {
    loading.value = true
    const data = {
      code: specSKU.value,
      limit: specPage.value.size,
      name: specName.value,
      page: specPage.value.current,
    }
    if (nodekey == '1') {
      await getProductSpec(data, route.params.id).then((res) => {
        specList.value = res.data.data.rows
        specTotal.value = parseInt(res.data.data.total)
        loading.value = false
      })
    } else {
      await getSpareSpec(data, route.params.id).then((res) => {
        specList.value = res.data.data.rows
        specTotal.value = parseInt(res.data.data.total)
        loading.value = false
      })
    }
  }

  // 获取BOM清单
  const getBomData = async () => {
    loading.value = true
    await getProductBoom(proInfo.value.id).then((res) => {
      tableData.value = res.data.data.rows
      loading.value = false
    })
  }

  // 获取子件数据
  const getChildList = async () => {
    bomLoading.value = true
    const data = {
      limit: pagination.value?.size == undefined ? 0 : pagination.value?.size,
      page: pagination.value?.current == undefined ? 0 : pagination.value?.current,
    }
    await getProductBoomChildList(data, boomId.value).then((res) => {
      selfData.value = []
      res.data.data.rows.forEach((item) => {
        selfData.value.push({
          class: String(item.type),
          id: item.id,
          brand: item.brand,
          code: item.code,
          goodsId: item.goodsId,
          goodsSpecId: item.goodsSpecId,
          model: item.model,
          name: item.name,
          num: item.qty,
          unit: item.unit,
          type: item.goodsType,
          specId: item.goodsSpecId,
          specName: item.specName,
          specCode: item.specCode,
          image: item.image,
          remark: item.remark,
        })
      })
      bomLoading.value = false
    })
  }

  // 查看清单详细
  const viewBomDetal = async (id) => {
    loading.value = true
    boomId.value = id
    await getProductBoomDetail(id).then(async (res) => {
      tableData2[0].spec = await res.data.data.row.productSpecId
      tableData2[0].notes = await res.data.data.row.remark
    })
    getChildList()
    loading.value = false
    bomDialog.value = true
  }

  // 将JSON转为字符串
  const getString = (str) => {
    if (str?.startsWith(`[`) == true) {
      if (JSON.parse(str).length <= 1) {
        if (JSON.parse(str)[0] instanceof Array) {
          return JSON.parse(str)[0].join()
        } else {
          return JSON.parse(str)[0]
        }
      } else {
        return JSON.parse(str).join()
      }
    } else {
      return str
    }
  }

  // 获取参数列表
  const getParaData = async () => {
    loading.value = true
    if (nodekey == '1') {
      await getProductParam(route.params.id).then((res) => {
        paramsName.value = res.data.data.row.name
        paramFields.value = res.data.data.row.paramFields
        if (paramFields.value) {
          paramFields.value.forEach((item) => {
            item.val = getString(item.val)
          })
        }
        customParams.value = res.data.data.row.customParams
        loading.value = false
      })
    } else {
      await getSparePara(route.params.id).then((res) => {
        paramsName.value = res.data.data.row.name
        paramFields.value = res.data.data.row.paramFields
        if (paramFields.value) {
          paramFields.value.forEach((item) => {
            item.val = getString(item.val)
          })
        }
        customParams.value = res.data.data.row.customParams
        loading.value = false
      })
    }
  }

  // 获取说明书列表
  const getInsData = async () => {
    loading.value = true
    await getInsList(getPagingData(insPage.value, insName.value), route.params.id).then((res) => {
      insList.value = res.data.data.rows
      insTotal.value = parseInt(res.data.data.total)
      loading.value = false
    })
  }

  // 获取视频列表
  const geVideoData = async () => {
    loading.value = true
    await getVideoList(getPagingData(videoPage.value, videoName.value), route.params.id).then(
      (res) => {
        videoList.value = res.data.data.rows
        videoTotal.value = parseInt(res.data.data.total)
        loading.value = false
      },
    )
  }

  // 获取商品内容简介
  const getProContent = async () => {
    loading.value = true
    if (nodekey == '1') {
      await getIntroduce(route.params.id).then((res) => {
        proContent.value = res.data.data.row
        loading.value = false
      })
    } else {
      await getSpareIntroduce(route.params.id).then((res) => {
        proContent.value = res.data.data.row
        loading.value = false
      })
    }
  }

  onMounted(() => {
    getProDetail()
    getSpecData()
  })

  // 新增BOM关联
  const addBOM = () => {
    bomDialog.value = true
    selfData.value = [
      {
        class: '1',
        id: null,
        brand: '',
        code: '',
        goodsId: '',
        goodsSpecId: '',
        model: '',
        name: '',
        num: '1',
        unit: '',
        type: '',
        specId: '',
        specName: '',
        specCode: '',
        image: '',
        remark: '',
      },
    ]
  }

  // 删除子件
  const deleteLineData = (index, id) => {
    if (selfData.value.length <= 1) {
      return false
    }
    selfData.value = selfData.value.filter((o, i) => i != index)
    selecttion.value = selecttion.value.filter((o, i) => i != index)
    delBoomChildIds.value.push(id)
  }

  // 添加子件
  const addLineData = () => {
    selfData.value.push({
      class: '1',
      id: null,
      brand: '',
      code: '',
      goodsId: '',
      goodsSpecId: '',
      model: '',
      name: '',
      num: '1',
      unit: '',
      type: '',
      specId: '',
      specName: '',
      specCode: '',
      image: '',
      remark: '',
    })
  }

  // 获取关联商品
  const getContPro = (name, i) => {
    typeName.value = name
    bomIndex.value = i
    selecttion.value = []
    brand.value = ''
    type.value = ''
    input5.value = ''
    relevanceDialog.value = true
    const seletc = {
      limit: 0,
      name: '',
      page: 0,
    }
    brandPageSelect(seletc).then((res) => {
      brandOptions.value = res.data.data.rows
    })
    typePageSelect(seletc).then((res) => {
      typeOptions.value = res.data.data.rows
    })
    getContData()
  }

  // 获取列表数据
  const getContData = () => {
    dataLoading.value = true
    const data = {
      branId: brand.value == undefined ? '' : brand.value,
      keyword: input5.value,
      limit: pagination2.value?.size == undefined ? 0 : pagination2.value?.size,
      page: pagination2.value?.current == undefined ? 0 : pagination2.value?.current,
      typeId: type.value == undefined ? '' : type.value,
    }
    contData.value = []
    if (typeName.value == '1') {
      getGoodsBoomList(data, proInfo.value.id).then((res) => {
        res.data.data.rows.forEach((item) => {
          if (contData.value.includes(item) == false) {
            contData.value.push({
              class: typeName.value,
              id: item.id,
              brand: item.brand,
              code: item.code,
              model: item.model,
              name: item.name,
              num: '1',
              unit: item.unit,
              type: item.type,
              specId: item.specId,
              specName: item.specName,
              specCode: item.specCode,
              image: item.image,
            })
          }
        })
        typeTotal2.value = parseInt(res.data.data.total)
        dataLoading.value = false
      })
    } else {
      getSpareBoomList(data).then((res) => {
        res.data.data.rows.forEach((item) => {
          if (contData.value.includes(item) == false) {
            contData.value.push({
              class: typeName.value,
              id: item.id,
              brand: item.brand,
              code: item.code,
              model: item.model,
              name: item.name,
              unit: item.unit,
              type: item.type,
              specId: item.specId,
              specName: item.specName,
              specCode: item.specCode,
              image: item.image,
            })
          }
        })
        typeTotal2.value = parseInt(res.data.data.total)
        dataLoading.value = false
      })
    }
  }

  // 选中关闭
  const closeSelect = () => {
    saveBtn(1)
  }

  // 选中保存
  const saveBtn = (n) => {
    if (selecttion.value.length == 0) {
      ElMessage({
        message: `请选择要关联的数据`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    if (selecttion.value.length == 1) {
      selecttion.value.forEach((item) => {
        if (selfData.value.includes(item) == false) {
          selfData.value[bomIndex.value] = {
            class: typeName.value,
            id: null,
            brand: item.brand,
            code: item.code,
            goodsId: item.id,
            goodsSpecId: item.specId,
            model: item.model,
            name: item.name,
            num: '1',
            unit: item.unit,
            type: item.type,
            specId: item.specId,
            specName: item.specName,
            specCode: item.specCode,
            image: item.image,
            remark: '',
          }
        }
      })
    } else {
      selfData.value.splice(bomIndex.value, 1)
      selecttion.value.forEach((item) => {
        selfData.value.push({
          class: typeName.value,
          id: null,
          brand: item.brand,
          code: item.code,
          goodsId: item.id,
          goodsSpecId: item.specId,
          model: item.model,
          name: item.name,
          num: '1',
          unit: item.unit,
          type: item.type,
          specId: item.specId,
          specName: item.specName,
          specCode: item.specCode,
          image: item.image,
          remark: '',
        })
      })
    }
    if (n == 1) {
      relevanceDialog.value = false
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item) == -1) {
          selecttion.value.push(item)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 批量填充数量
  const changeNumber = () => {
    if (num.value) {
      selfData.value.forEach((item) => {
        item.num = num.value
      })
    }
  }

  // 保存BOM关联
  const saveBOM = () => {
    bomLoading.value = true
    boomChildVos.value = []
    selfData.value.forEach((item) => {
      boomChildVos.value.push({
        id: item.id == undefined ? null : item.id,
        goodsId: item.goodsId,
        goodsSpecId: item.goodsSpecId,
        qty: item.num,
        remark: item.remark,
        type: item.class,
      })
    })
    const data = {
      boomChildVos: boomChildVos.value,
      delBoomChildIds: delBoomChildIds.value,
      id: boomId.value == undefined ? null : boomId.value,
      productId: proInfo.value.id,
      productSpecId: tableData2[0].spec,
      remark: tableData2[0].notes,
    }
    saveGoodsBoom(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        bomDialog.value = false
        bomLoading.value = false
      } else {
        if (res.data.isError)
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
        bomLoading.value = false
        return
      }
    })
  }

  // 按钮取消聚焦
  const btnCancelFocus = (e: Event) => {
    ;(e.target as HTMLButtonElement).blur()
  }
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
